import { Injectable } from '@nestjs/common';
import { CreateAuthDto } from './dto/create-auth.dto';
import { UpdateAuthDto } from './dto/update-auth.dto';
import { DataSource } from 'typeorm';
import * as crypto from 'crypto'
import { userInfo } from 'src/userInfo.entity';
import { MailerService } from '@nestjs-modules/mailer';


@Injectable()
export class AuthService {
  constructor(
    private dataSource: DataSource,
    private readonly mailerService: MailerService
  ) {
  }


  public example(subject: string, text: string, html: string, to: string): void {
    console.log("发送")
    this.mailerService
      .sendMail({
        to: to,
        from: '',
        subject: subject,
        text: text,
        html: html,
      })
      .then((res) => {
        console.log(res)
      })
      .catch((res) => {
        console.log(res)
      });
  }


  async login(body: any): Promise<any>{
    let hmac = crypto.createHmac("sha1", "salt");
    let password = hmac.update(body.password).digest().toString('base64');
    // 去除用户名两边空格
    let username = body.username.toString().trim();
    const userOne = await this.dataSource.manager.findOneBy(userInfo, {
        name: username,
        password: password,
        flag: "1",
    })
    if(userOne == null){
        return {
            code: 1,
            msg: "用户名或密码错误"
        }
    }else{
        return {
            code: 0,
            msg: "登录成功"
        }
    }
  }

  async enroll(body: any): Promise<any> {
    const userOne = await this.dataSource.manager.findOneBy(userInfo, {
        name: body.username,
        flag: "1",
    })
    if(userOne == null){
        let hmac = crypto.createHmac("sha1", "salt");
        console.log(body.password);
        let password = hmac.update(body.password).digest().toString('base64');
        const user = new userInfo();
        user.name = body.username
        user.flag = "1"
        user.email = body.email;
        user.password = password
        this.example('主题', '主题', '内容', body.email);
        const res = await this.dataSource.manager.save(user)
        if(!res){
            return {"err": 500, msg: "注册错误"};
        }else{
            return {"err": 200, msg: "注册成功"}
        }
    }else{
        return {"err": 500, msg : "用户已存在"}
    }
    
    
  }
}
